const crypto = require('crypto'),
    path = require('path'),
    url = require('url'),
    wechat = require('../config/config').wechat;

/**
 * @author:ares
 * @datetime:2018/4/4 12:49
 * @description: sha1加密字符串
 * @param {string} str   待加密的字符串
 * @returns {string}
 */
function sha1(str) {
    let shasum = crypto.createHash("sha1");
    shasum.update(str);
    str = shasum.digest("hex");
    return str;
}

/**
 * @author:ares
 * @datetime:2018/4/4 12:49
 * @description: 验证开发者服务器
 * @param {object} req  请求
 * @param {object} res  响应
 */
function authServer(req, res) {
    console.log('>>>>authService<<<<')
    let query = url.parse(req.url, true).query,
        signature = query.signature,
        echostr = query.echostr,
        timestamp = query['timestamp'],
        nonce = query.nonce,
        reqArray = [nonce, timestamp, wechat.token];
   
    //对数组进行字典排序
    reqArray.sort();
    let sortStr = reqArray.join(''),
        sha1Str = sha1(sortStr);

    if (signature === sha1Str) {
	    console.log("授权成功!");
        res.end(echostr);
    } else {
        res.end("false");
        console.log("授权失败!");
    }
}


module.exports = authServer;